package com.cqupt.service.impl;

import com.cqupt.exception.BusinessException;
import com.cqupt.model.vo.ResultCodeEnum;
import com.cqupt.model.vo.ScoreVO;
import com.cqupt.model.vo.SpeakVO;
import com.cqupt.service.FileService;
import com.cqupt.service.SparkService;
import com.cqupt.service.SpeakService;
import jakarta.annotation.Resource;
import javazoom.spi.mpeg.sampled.file.MpegAudioFileReader;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.sound.sampled.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Service
public class SpeakServiceImpl implements SpeakService {

    @Resource
    private SparkService sparkService;

    @Resource
    private FileService fileService;


    @Override
    public SpeakVO chat(int id, MultipartFile file) {
        String text = sparkService.recognize(file);
        for (char c : text.toCharArray()) {
            if (Character.UnicodeScript.of(c) == Character.UnicodeScript.HAN) {
                throw new BusinessException(ResultCodeEnum.AUDIO_ILLEGAL);
            }
        }
        String head = "现在我会发送一段英文给你，你需要根据英文回复我。回复内容必须为英文，且只能是一段话，并且根据实际情景和上下文回复。下面是我传给你的英文内容：";
        String msg = head + text;
        String resText = sparkService.chat(id, msg);
        byte[] resAudio = sparkService.tts(resText);

        if (text.startsWith(" ")) {
            text = text.replaceFirst(" ", "");
        }
//        text = ("[content]\n" + text);
        ScoreVO scoreVO = sparkService.evaluate(file, text);

        SpeakVO speakVO = new SpeakVO();
        speakVO.setReqText(text);
        speakVO.setReqTranslation("");
        speakVO.setScoreVO(scoreVO);


        speakVO.setResText(resText);
        speakVO.setResTranslation("");
        speakVO.setAudio(resAudio);
        return speakVO;
    }

    @Override
    public void test(MultipartFile file) {
        try {
            // 将 MultipartFile 转换为 File
            File mp3File = convertMultipartFileToFile(file);
//            String url = fileService.upload(file);
            // 获取文件的音频流，pcm的格式
            AudioInputStream audioInputStream = getPcmAudioInputStream(mp3File.getAbsolutePath());
            // 将音频转化为 pcm的格式保存下来
            AudioSystem.write(audioInputStream, AudioFileFormat.Type.WAVE, new File("./temp.pcm"));

        } catch (IOException e) {
            e.printStackTrace();

        }


    }

    private File convertMultipartFileToFile(MultipartFile multipartFile) throws IOException {
        File file = new File(System.getProperty("java.io.tmpdir") + "/" + multipartFile.getOriginalFilename());
        multipartFile.transferTo(file);
        return file;
    }

    private static AudioInputStream getPcmAudioInputStream(String mp3filepath) {
        File mp3 = new File(mp3filepath);
        AudioInputStream audioInputStream = null;
        AudioFormat targetFormat = null;
        AudioInputStream in = null;
        try {

            // 读取音频文件的类
            MpegAudioFileReader mp = new MpegAudioFileReader();
            in = mp.getAudioInputStream(mp3);
            AudioFormat baseFormat = in.getFormat();

            // 设定输出格式为pcm格式的音频文件
            targetFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, baseFormat.getSampleRate(), 16,
                    baseFormat.getChannels(), baseFormat.getChannels() * 2, baseFormat.getSampleRate(), false);

            // 输出到音频
            audioInputStream = AudioSystem.getAudioInputStream(targetFormat, in);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return audioInputStream;
    }
}
